package com.hl.card.pay.util;

import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.util.Map;

public class HttpTool {

    /**
     * 使用json编码
     * @param url
     * @param jsonObject
     * @param restTemplate
     * @return
     */
    public  static String post(String url, JSONObject jsonObject, RestTemplate restTemplate){
        HttpHeaders headers = new HttpHeaders();
        MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
        headers.setContentType(type);
        headers.add("Accept", MediaType.APPLICATION_JSON.toString());
        HttpEntity<String> formEntity = new HttpEntity<String>(jsonObject.toString(), headers);
        String result = restTemplate.postForObject(url, formEntity, String.class);
        return result;
    }

    /**
     * 使用表单编码
     * @param url
     * @param jsonObject
     * @param restTemplate
     * @return
     */
    public  static JSONObject postJSONObject(String url, JSONObject jsonObject, RestTemplate restTemplate){
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        MultiValueMap map= new LinkedMultiValueMap<>();
        for(Map.Entry entry:jsonObject.entrySet()){
            map.add(entry.getKey(),entry.getValue());
        }
        HttpEntity<MultiValueMap> request = new HttpEntity<>(map, headers);
        String str = restTemplate.postForEntity(url, request, String.class).getBody();
        JSONObject result=  JSONObject.parseObject(str);
        return result;
    }








}
